package com.atguigu.gmall.cart.controller;

import com.atguigu.gmall.cart.pojo.Cart;
import com.atguigu.gmall.cart.service.CartService;
import com.atguigu.gmall.common.bean.ResponseVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.List;

@Controller
public class CartController {
    @Autowired
    private CartService cartService;

    @GetMapping
    public String addCart(Cart cart) {
        cartService.addCart(cart);
        //添加成功 重定向到 该路径
        return "redirect:http://cart.gmall.com/addCart.html?skuId=" + cart.getSkuId() + "&count=" + cart.getCount();
    }

    @GetMapping("addCart.html")
    public String queryCartBySkuId(Cart cart, Model model) {
        BigDecimal count = cart.getCount(); //本次新增的数量
        cart = cartService.queryCartBySkuId(cart.getSkuId());
        cart.setCount(count); //添加购物车成功页面显示的数量 即  -> 本次新增数量

        model.addAttribute("cart", cart);
        return "addCart";
    }

    @GetMapping("cart.html")
    public String queryCart(Model model){
        List<Cart> carts = cartService.queryCart();
        model.addAttribute("carts",carts);

        return "cart";
    }

    @PostMapping("updateNum")
    @ResponseBody
    public ResponseVo updateNum(@RequestBody Cart cart){
        cartService.updateNum(cart);
        return ResponseVo.ok();
    }

    @PostMapping("deleteCart")
    @ResponseBody
    public ResponseVo deleteCart(@RequestParam("skuId")Long skuId){
        cartService.deleteCart(skuId);
        return ResponseVo.ok();
    }

}
